package com.dorm.cj.persistence.config;

import com.dorm.cj.persistence.pojo.Configuration;
import com.dorm.cj.persistence.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseMapper(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> selectNodes = rootElement.selectNodes("//select");
        for (Element element : selectNodes) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sqlText = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sqlText);

            String key = namespace + "." + id;

            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }

    /**
     <mapper namespace="com.lagou.dao.IUserDao">
     <!--sql的唯一标识：namespace.id来组成 ： statementId-->
     <select id="findAll" resultType="com.lagou.pojo.User" >
     select * from user
     </select>

     <select id="findByCondition" resultType="com.lagou.pojo.User" parameterType="com.lagou.pojo.User">
     select * from user where id = #{id} and username = #{username}
     </select>
     </mapper>
     */
}
